package com.ruoyi.app.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.app.service.IPromotionCodeService;
import com.ruoyi.app.service.PasswordService;
import com.ruoyi.app.service.imp.PromotionCodeServiceImp;
import com.ruoyi.app.utils.RandomUtil;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * 用户
 * @Author Alan Zhang
 * @Date 2025/3/15 13:20
 */
@RestController
@RequestMapping("/api/user")
public class UserApiController extends BaseApiController{

    @Autowired
    private IJtUserAddressService jtUserAddressService;
    @Autowired
    private IJtMyDevicesService jtMyDevicesService;
    @Autowired
    private IJtCommissionDetailService jtCommissionDetailService;
    @Autowired
    private IJtOrderService jtOrderService;
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private IPromotionCodeService promotionCodeService;


    //========== 用户信息 =========
    @PostMapping("/info")

    public AjaxResult info()
    {
        String username = JwtUtils.getUserName(getToken());
        JtAppUser jtAppUser = jtAppUserService.selectUserByPhoneNumber(username);
        return AjaxResult.success("success", jtAppUser);
    }

    //========== 订单管理 =========
    @PostMapping("/myOrder/list")
    public AjaxResult myOrderList(Integer orderStatus, String orderNo , String startTime, String endTime)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        JtOrder param = new JtOrder();
        param.setUserId(jtAppUser.getUserId());
        param.setOrderNo(orderNo);
        param.setOrderStatus(orderStatus);

        param.getParams().put("beginCreateTime", startTime);
        param.getParams().put("endCreateTime", endTime);

        PageUtils.startPage();
        //排序字段
        PageHelper.orderBy("create_time desc");
        List<JtOrder> jtOrderList = jtOrderService.selectJtOrderAndItemList(param);
        TableDataInfo tableDataInfo = getDataTable(jtOrderList);
        return AjaxResult.success("success", tableDataInfo);
    }

    //========== 地址管理 =========
    @PostMapping("/myAddress/list")
    public AjaxResult myAddress(String receiver)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        JtUserAddress userAddress = new JtUserAddress();
        userAddress.setUserId(jtAppUser.getUserId());
        userAddress.setReceiver(receiver);
        List<JtUserAddress> addressList = jtUserAddressService.selectJtUserAddressList(userAddress);
        return AjaxResult.success("success", addressList);
    }

    @PostMapping("/myAddress/add")
    public AjaxResult addMyAddress(JtUserAddress userAddress)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        StringBuilder msgSb = new StringBuilder();
        if(StringUtils.isEmpty(userAddress.getCountry())){
            msgSb.append("请填写国家");
        }
        if(StringUtils.isEmpty(userAddress.getProvince())){
            msgSb.append("请填写省份");
        }
        if(StringUtils.isEmpty(userAddress.getCity())){
            msgSb.append("请填写城市");
        }
        if(StringUtils.isEmpty(userAddress.getFullAddress())){
            msgSb.append("请填写详细地址");
        }
        if(StringUtils.isEmpty(userAddress.getPhoneNumber())){
            msgSb.append("请填写联系电话");
        }
        if(StringUtils.isEmpty(userAddress.getReceiver())){
            msgSb.append("请填写收件人");
        }
        if(msgSb.length() > 0) {
            return AjaxResult.error(msgSb.toString());
        }
        if(1 == userAddress.getDefaultStatus()) {
            int updateRows = jtUserAddressService.updateJtUserAddressCancelDefault(jtAppUser.getUserId());
        }

        userAddress.setUserId(jtAppUser.getUserId());
        int rows = jtUserAddressService.insertJtUserAddress(userAddress);
        if(rows > 0) {
            return AjaxResult.success("保存成功");
        } else {
            return AjaxResult.error("保存失败");
        }
    }

    @PostMapping("/myAddress/edit")
    public AjaxResult editMyAddress(Long addressId, JtUserAddress userAddress)
    {
        JtAppUser jtAppUser = getTokenAppUser();
        JtUserAddress dbUserAddress = jtUserAddressService.selectJtUserAddressByAddressId(addressId);
        if(dbUserAddress.getUserId().equals(jtAppUser.getUserId())){

            if(dbUserAddress.getDefaultStatus() == 0 && userAddress.getDefaultStatus() == 1){
                int updateRows = jtUserAddressService.updateJtUserAddressCancelDefault(jtAppUser.getUserId());
            }

            userAddress.setUserId(dbUserAddress.getUserId());
            int rows = jtUserAddressService.updateJtUserAddress(userAddress);
            if(rows > 0){
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.success("修改失败");
            }
        } else {
            return AjaxResult.error("修改失败");
        }
    }

    @PostMapping("/myAddress/delete")
    public AjaxResult deleteMyAddress(Long addressId)
    {
        JtAppUser jtAppUser = getTokenAppUser();
        JtUserAddress dbUserAddress = jtUserAddressService.selectJtUserAddressByAddressId(addressId);
        if(dbUserAddress.getUserId().equals(jtAppUser.getUserId())){
            int rows = jtUserAddressService.deleteJtUserAddressByAddressId(addressId);
            if(rows > 0) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.success("删除失败");
            }
        } else {
            return AjaxResult.success("删除失败");
        }
    }

    //========== 设备管理 =========
    @PostMapping("/device/list")
    public AjaxResult deviceList()
    {
        JtAppUser jtAppUser = getTokenAppUser();

        JtMyDevices param = new JtMyDevices();
        param.setUserId(jtAppUser.getUserId());
        List<JtMyDevices> myDevicesList = jtMyDevicesService.selectJtMyDevicesList(param);
        return AjaxResult.success("device list success", myDevicesList);
    }

    //绑定设备
    @PostMapping("/device/add")
    public AjaxResult addDevice(String deviceSn, String name)
    {
        if(StringUtils.isEmpty(deviceSn)){
            return AjaxResult.error("设备序列号不能为空！");
        }
        JtAppUser jtAppUser = getTokenAppUser();

        JtMyDevices jtMyDevices = new JtMyDevices();
        jtMyDevices.setUserId(jtAppUser.getUserId());
        jtMyDevices.setDeviceSn(deviceSn);
        jtMyDevices.setName(name);
        int rows = jtMyDevicesService.insertJtMyDevices(jtMyDevices);
        if(rows > 0) {
            return AjaxResult.success("add device success");
        } else {
            return AjaxResult.error("添加失败！");
        }
    }



    //========== 推广 明细 =========
    @PostMapping("/promotion/list")
    public AjaxResult promotionList(Integer type, String startTime, String endTime, int pageNum, int pageSize)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        JtCommissionDetail param = new JtCommissionDetail();
        param.setUserId(jtAppUser.getUserId());
        param.setStatus(type);// 1 收入 2 提现
        param.getParams().put("startTime", startTime);
        param.getParams().put("endTime", endTime);

        PageUtils.startPage();
        //排序字段
        PageHelper.orderBy("create_time desc");
        List<JtCommissionDetail>  commissionDetailList = jtCommissionDetailService.selectJtCommissionDetailList(param);
        TableDataInfo tableDataInfo = getDataTable(commissionDetailList);
        return AjaxResult.success("success", tableDataInfo);
    }


    /**
     * 切换语言
     * @param lang
     * @return
     */
    @PostMapping("/change/language")
    public AjaxResult changeLang(String lang){
        JtAppUser appUser = getTokenAppUser();

        JtAppUser jtAppUser = new JtAppUser();
        jtAppUser.setUserId(appUser.getUserId());
        jtAppUser.setLang(lang);
        int rows = jtAppUserService.updateJtAppUser(jtAppUser);
        if(rows > 0){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }


    @PostMapping("/reset/pwd")
    @ResponseBody
    public AjaxResult resetPwd(String oldPassword, String newPassword)
    {
        String username = JwtUtils.getUserName(getToken());
        JtAppUser jtAppUser = jtAppUserService.selectUserByPhoneNumber(username);

        JtAppUser user = new JtAppUser();
        user.setUserId(jtAppUser.getUserId());
        if (!passwordService.matches(user, oldPassword))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (passwordService.matches(user, newPassword))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(jtAppUser.getPhoneNumber(), newPassword, user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        if (jtAppUserService.resetUserPwd(user) > 0)
        {
            //setSysUser(jtAppUserService.selectJtAppUserList(user.getUserId()));
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }


    //========== 推广码绑定=========
    @PostMapping("/promotion/bind")
    public AjaxResult promotionBind(String promotionCode)
    {
        String username = JwtUtils.getUserName(getToken());
        JtAppUser jtAppUser = jtAppUserService.selectUserByPhoneNumber(username);

        if(StringUtils.isEmpty(promotionCode)){
            return AjaxResult.error("推广码不能为空！");
        }
        if(jtAppUser.getPromotionCode().equals(promotionCode)){
            return AjaxResult.error("用户不能绑定自己的推广码！");
        }
        return promotionCodeService.promotionBindUser(jtAppUser, promotionCode);
    }
}
